package zqtools;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class NetUtil {
    public static JSONObject f_get1(String url) {
        String result = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 发送请求
            CloseableHttpResponse r = httpclient.execute(httpget);

            // 得到响应体
            HttpEntity entity = r.getEntity();
            result = EntityUtils.toString(entity);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != httpclient) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return JSONObject.fromObject(result);
    }

    public static JSONObject f_get2(String url) throws IOException {
        try {
            URL urlobj = new URL(url);
            URLConnection urlConnection = urlobj.openConnection();
            InputStream is = urlConnection.getInputStream();

            byte[] b = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = is.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }
            return JSONObject.fromObject(sb.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static JSONObject f_post1(String url, String arg) {
        String result = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse httpresponse;

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        try {
            StringEntity entity = new StringEntity(arg, StandardCharsets.UTF_8);
            entity.setContentEncoding("UTF-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/json");
//            httpPost.setEntity(new StringEntity(arg, ContentType.create("application/json", StandardCharsets.UTF_8)));
            httpPost.setEntity(entity);
            httpresponse = httpclient.execute(httpPost);
            if (httpresponse != null && httpresponse.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(httpresponse.getEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != httpclient) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return JSONObject.fromObject(result);
    }

    public static JSONObject f_post2(String url, byte[] arg){
        StringBuilder sb = new StringBuilder();

        try {
            URL urlobj = new URL(url);

            HttpURLConnection urlConnection = (HttpURLConnection) urlobj.openConnection();
            //urlConnection.setRequestProperty("contentType", "UTF-8");
            urlConnection.setRequestProperty("contentType","application/json");
            urlConnection.setConnectTimeout(5000);
            //要发送数据出去，必须要设置为可发送数据状态
            urlConnection.setDoOutput(true);

            //获取输出流
            OutputStream os = urlConnection.getOutputStream();

            //写输出数据
            os.write(arg);
//            os.write(arg.getBytes());
//            os.write(new String(arg.getBytes(StandardCharsets.UTF_8),));
//            new String(jsonObj.toString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.ISO_8859_1)
            os.close();

            //获取输入流，也就是接口返回来的数据
            int li_code = urlConnection.getResponseCode();
            if ((li_code != HttpURLConnection.HTTP_OK) && (li_code != HttpURLConnection.HTTP_CREATED) && (li_code != HttpURLConnection.HTTP_ACCEPTED)) {
                System.out.println("网络接口不正确..." + li_code);
            } else {
                urlConnection.setReadTimeout(5000);
                InputStream is = urlConnection.getInputStream();

                byte[] b = new byte[1024];
                int len;
                while ((len = is.read(b)) != -1) {
                    sb.append(new String(b, 0, len));
                }
                is.close();
            }
            urlConnection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e){
            if ("connect timed out".equals(e.getMessage())) {
                System.out.println("连接网址超时，请检查网络...");
            }
            else if ("Connection refused: connect".equals(e.getMessage())) {
                System.out.println("连接被拒绝，请检查网络...");
            }
        }

        if (sb.length() == 0) {
            return new JSONObject();
        } else {
            return JSONObject.fromObject(sb.toString());
        }
    }

    //--POST3针对android对服务器请求而用的一种方式, 同时服务器端的接收程序也进行了重写
    //--主要是服务端的接收程序，原来的f_post2在接收数据包的时候没有循环遍历，接收不完整
    public static JSONObject f_post3(String url, JSONObject arg) throws IOException {

        StringBuilder sb = new StringBuilder();
        try {
            URL urlobj = new URL(url);

            HttpURLConnection urlConnection = (HttpURLConnection) urlobj.openConnection();
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            urlConnection.setConnectTimeout(5000);
            //要发送数据出去，必须要设置为可发送数据状态
            urlConnection.setDoOutput(true);

            //获取输出流
            OutputStream os = urlConnection.getOutputStream();

            //写输出数据
            os.write(arg.toString().getBytes());
            os.close();

            //获取输入流，也就是接口返回来的数据
            int li_code = urlConnection.getResponseCode();
            if ((li_code != HttpURLConnection.HTTP_OK) && (li_code != HttpURLConnection.HTTP_CREATED) && (li_code != HttpURLConnection.HTTP_ACCEPTED)) {
                System.out.println("网络接口不正确..." + li_code);
                JSONObject jret = new JSONObject();
                JSONObject jsub = new JSONObject();
                jsub.put("VALUE01", "ZZ01");
                jsub.put("VALUE02", "网络接口错误3...");
                jsub.put("VALUE03", "0");
                JSONArray jr = new JSONArray();
                jr.add(jsub);
                jret.put("db1", jr);
                return jret;
            } else {
                urlConnection.setReadTimeout(5000);
                InputStream is = urlConnection.getInputStream();

                byte[] b = new byte[1024];
                int len;
                while ((len = is.read(b)) != -1) {
                    sb.append(new String(b, 0, len));
                }
                is.close();
            }
            urlConnection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            JSONObject jret = new JSONObject();
            JSONObject jsub = new JSONObject();
            jsub.put("VALUE01", "ZZ01");
            jsub.put("VALUE02", "网络错误...");
            JSONArray jr = new JSONArray();
            jr.add(jsub);
            jret.put("db1", jr);
            return jret;
        } catch (IOException e) {
            System.out.println("链接服务器错误，请检查网络...");
            JSONObject jret = new JSONObject();
            JSONObject jsub = new JSONObject();
            jsub.put("VALUE01", "ZZ01");
            jsub.put("VALUE02", "网络错误...");
            JSONArray jr = new JSONArray();
            jr.add(jsub);
            jret.put("db1", jr);
            return jret;
        }

        if (sb.length() == 0) {
            return new JSONObject();
        } else {
            return JSONObject.fromObject(sb.toString());
        }
    }
}
